/*

 Authors: ZhangXuelian
 	
 
 Changes:
 	
	
*/

#ifndef __MSG_RESULT_H_
#define __MSG_RESULT_H_

#include "coe_comm.h"

#include <limits.h>
#include <pthread.h>

#define INFINITE		0xFFFFFFFF
#define ETIMEDOUT       145
#define NEW_MSG_RESULT() new_msg_result(INFINITE)

typedef struct 
{
	int var;
	pthread_cond_t cond;
	pthread_mutex_t mutex;
}THREAD_EVENT, *EVENT;


EVENT create_event();
void delete_event(EVENT ev);
int wait_event(EVENT ev, unsigned long wait_time);
signed char set_event(EVENT ev);

// ----------------
typedef struct tagMsgResult
{
	EVENT event;
	int result;
	unsigned long wait_time;
} MSG_RESULT;


static __inline MSG_RESULT * new_msg_result(unsigned long wait_time)
{
	MSG_RESULT * msg_result;
	if (NULL == (msg_result = (MSG_RESULT *)my_malloc(sizeof(MSG_RESULT))))
		return NULL;
	if (NULL == (msg_result->event = create_event()))
	{
		my_free(msg_result);
		return NULL;
	}
	msg_result->result = 0;
	msg_result->wait_time = wait_time;
	return msg_result;
}

static __inline void delete_msg_result(MSG_RESULT * msg_result)
{
	delete_event(msg_result->event);
	my_free(msg_result);
}

#define WAIT_TIMEOUT	ETIMEDOUT
static __inline int get_msg_result(MSG_RESULT * msg_result)
{
	int result;

	if (WAIT_TIMEOUT == wait_event(msg_result->event, msg_result->wait_time))
	{
		result = ERROR_REQ_TIMEOUT;
	}
	else
	{
		result = msg_result->result;
	}

	delete_event(msg_result->event);
	my_free(msg_result);
	return result;
}

#endif
